package com.veo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.veo.entity.Address;
import com.veo.entity.User;
import com.veo.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private AddressService addressService;

    @RequestMapping("/add")
    @ResponseBody
    public String add(Address address, HttpSession session){
        User user = (User) session.getAttribute("user");
        address.setUserId(user.getId());
        if (address.getIsDefault() != null && "on".equals(address.getIsDefault())){
            address.setIsDefault("1");
            QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_default",1);
            Address oldAddress = addressService.getOne(queryWrapper);
            oldAddress.setIsDefault("0");
            addressService.updateById(oldAddress);
        }
        addressService.save(address);
        return "success";
    }
}
